<?php
final class VoteImpl
{
	static function addVote($type, $name, array $data)
	{
		$data['vote_guid'] = sha1(rand(1000, 9999).uniqid().rand(1000, 9999));

		if (!isset($data['vote_allow_num'])) {
			$data['vote_allow_num'] = 1;
		}

		if (!isset($data['access_type'])) {
			$data['access_type'] = VoteConst::ACCESS_TYPE_PUBLIC;
		}

		if ($data['access_type'] == VoteConst::ACCESS_TYPE_TOKEN) {
			$data['access_token'] = self::get_access_token();
		}

		if (isset($data['create_ip']) && !is_int($data['create_ip'])) {
			$data['create_ip'] = sprintf('%u', ip2long($data['create_ip']));
		}

		if (isset($data['vote_begin']) && isset($data['vote_end']) && $data['vote_begin'] < $data['vote_end']) {
			throw new Exception('vote.u_endTimeMustBiggerThanBeginTime');
		}
		$data['create_time'] = time();

		if (!isset($data['vote_status'])) {
			$data['vote_status'] = 1;
		} else {
			$data['vote_status'] = intval($data['vote_status']);
		}

		$db = Db::get('ts_vote');
		$db->table('v_vote')->unique('vote_id')->saveBody($data)->insert();
		return array(
			'vote_id' 		=> $db->getLastInsertId(),
			'vote_guid'	=> $data['vote_guid'],
		); 
	}

	static function getVote($voteId)
	{
		$where = array('vote_status!' => -1);
		if (strlen($voteId) == 40) {
			$where['vote_guid'] = $voteId;
		} else {
			$where['vote_id'] = intval($voteId);
		}
		$rows = Db::get('ts_vote')->table('v_vote')->where($where)->get();
		if (empty($rows)) {
			return false;
		}
		$row = array_shift($rows);
		$row['vote_cover'] = bin2hex($row['vote_cover']);
		return $row;
	}

	static function updateVote($voteId, array $data)
	{
		if (strlen($voteId) == 40) {
			$where['vote_guid'] = $voteId;
		} else {
			$where['vote_id'] = intval($voteId);
		}

		if (isset($data['vote_begin']) && isset($data['vote_end']) && $data['vote_begin'] < $data['vote_end']) {
			throw new Exception('vote.u_endTimeMustBiggerThanBeginTime');
		}

		$body = array();
		foreach(array('vote_type', 'vote_status', 'vote_summary', 'vote_cover', 'vote_allow_num', 'access_type', 'access_token', 'access_begin', 'access_stop') as $key) {
			if (isset($data[$key])) {
				$body[$key] = $data[$key];
			}
		}
		if (empty($body)) {
			return;
		}

		Db::get('ts_vote')->table('v_vote')->where($where)->saveBody($body)->update();
	}

	static function resetAccessToken($voteId)
	{
		$token = self::get_access_token();
		self::updateVote($voteId, array('access_token' => $token));
	}

	private static function get_access_token()
	{
		return md5(rand(1000, 9999).uniqid());
	}
}
